﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DataAccessLayer;
using DataAccessLayer.ImportDataSetTableAdapters;


namespace PresentationLayer
{
    public partial class DialogMapExcelColumn : Form
    {
        private OleDbDatabase.MappingTaskID mappingTaskID;
        private string excelFile;


        DataTable listColumnAvailableDataTable;
        ImportDataSet.ListColumnMappingDataTable listColumnMappingDataTable;


        ListColumnMappingTableAdapter listColumnMappingTableAdapter;
        private ListColumnMappingTableAdapter ListColumnMappingTableAdapter
        {
            get
            {
                if (listColumnMappingTableAdapter == null) listColumnMappingTableAdapter = new ListColumnMappingTableAdapter();
                return listColumnMappingTableAdapter;
            }
        }

        public DialogMapExcelColumn(OleDbDatabase.MappingTaskID mappingTaskID, string excelFile)
        {
            InitializeComponent();

            this.mappingTaskID = mappingTaskID;
            this.excelFile = excelFile;

            this.listColumnAvailableDataTable = new DataTable("ListColumnAvailable");
            this.listColumnAvailableDataTable.Columns.Add("SerialID", System.Type.GetType("System.Int32"));
            this.listColumnAvailableDataTable.Columns.Add("ColumnAvailableName", System.Type.GetType("System.String"));
            this.listColumnAvailableDataTable.Columns.Add("ColumnMappingName", System.Type.GetType("System.String"));
        }

        private void DialogMapExcelColumn_Load(object sender, EventArgs e)
        {
            try
            {
                //Get available column from current file
                DataTable excelDataTable = OleDbDatabase.OpenExcelSheet(this.excelFile, OleDbDatabase.GetMappingSheetName(this.mappingTaskID), "SELECT *", "");
                if (excelDataTable != null && excelDataTable.Columns.Count > 0)
                {
                    int i = 0;
                    foreach (DataColumn dataColumn in excelDataTable.Columns)
                    {
                        DataRow dataRow = this.listColumnAvailableDataTable.NewRow();
                        dataRow["SerialID"] = ++i;
                        dataRow["ColumnAvailableName"] = dataColumn.ColumnName;
                        dataRow["ColumnMappingName"] = "";
                        this.listColumnAvailableDataTable.Rows.Add(dataRow);
                    }
                }

                //Get required column (and saved mapping data)
                listColumnMappingDataTable = this.ListColumnMappingTableAdapter.GetData((int)this.mappingTaskID);

                //Remove un-matching from current file to saved mapping data before continue
                foreach (ImportDataSet.ListColumnMappingRow listColumnMappingRow in this.listColumnMappingDataTable.Rows)
                    if (listColumnMappingRow.ColumnMappingName != "")
                    {
                        DataRow[] foundDataRows = this.listColumnAvailableDataTable.Select("ColumnAvailableName = '" + listColumnMappingRow.ColumnMappingName + "'");
                        if (foundDataRows != null && foundDataRows.Length != 0)
                            foundDataRows[0]["ColumnMappingName"] = listColumnMappingRow.ColumnRequiedName;
                        else
                            listColumnMappingRow.ColumnMappingName = "";
                    }


                this.dataGridColumnAvailable.AutoGenerateColumns = false;
                this.dataGridColumnMapping.AutoGenerateColumns = false;

                //Binding
                this.dataGridColumnAvailable.DataSource = this.listColumnAvailableDataTable;
                this.dataGridColumnMapping.DataSource = this.listColumnMappingDataTable;
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void MapAndUnMapColumn(object sender, EventArgs e)
        {
            try
            {
                bool IsMap = sender.Equals(this.buttonMapColumn) ? true : false;
                DataRow listColumnAvailabeRow = null; DataRow[] foundDataRows = null;

                if (this.dataGridColumnMapping.CurrentRow != null)
                {
                    ImportDataSet.ListColumnMappingRow listColumnMappingRow = ((DataRowView)this.dataGridColumnMapping.CurrentRow.DataBoundItem).Row as ImportDataSet.ListColumnMappingRow;
                    if (listColumnMappingRow != null)//Check for a valid selected row
                    {
                        if (IsMap)
                        {
                            if (this.dataGridColumnAvailable.CurrentRow == null) return;
                            listColumnAvailabeRow = ((DataRowView)this.dataGridColumnAvailable.CurrentRow.DataBoundItem).Row;
                            if (listColumnAvailabeRow == null) return; //Check for a valid selected row

                            //Clear current mapping listColumnMappingDataTable
                            foundDataRows = this.listColumnMappingDataTable.Select("ColumnMappingName = '" + (string)listColumnAvailabeRow["ColumnAvailableName"] + "'");
                            foreach (ImportDataSet.ListColumnMappingRow foundDataRow in foundDataRows)
                                foundDataRow.ColumnMappingName = "";
                        }

                        //Clear current mapping listColumnAvailableDataTable
                        foundDataRows = this.listColumnAvailableDataTable.Select("ColumnMappingName = '" + listColumnMappingRow.ColumnRequiedName + "'");
                        foreach (DataRow foundDataRow in foundDataRows)
                            foundDataRow["ColumnMappingName"] = "";



                        if (IsMap)
                        {//Make a mapping
                            listColumnMappingRow.ColumnMappingName = (string)listColumnAvailabeRow["ColumnAvailableName"];
                            listColumnAvailabeRow["ColumnMappingName"] = listColumnMappingRow.ColumnRequiedName;
                        }
                        else//Clear current mapping listColumnMappingDataTable
                            listColumnMappingRow.ColumnMappingName = "";

                    }
                }

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            try
            {
                //Check for valid mapping: All columns map already
                DataRow[] foundDataRows = this.listColumnMappingDataTable.Select("ColumnMappingName = ''");
                if (foundDataRows != null && foundDataRows.Length != 0) throw new System.ArgumentException("All required columns must be mapped in order to continue.");

                ImportDataSet.ListColumnMappingDataTable listColumnMappingChangesDataTable = (ImportDataSet.ListColumnMappingDataTable)this.listColumnMappingDataTable.GetChanges();
                if (listColumnMappingChangesDataTable != null) //Save mapping column
                {
                    int rowsAffected = this.ListColumnMappingTableAdapter.Update(listColumnMappingChangesDataTable); 
                    if (rowsAffected != listColumnMappingChangesDataTable.Rows.Count) throw new System.ArgumentException("Error occur when update mapping column.");
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
                this.DialogResult = DialogResult.None;
            }
        }

    }
}
